package com.mojian.controller;

import com.mojian.common.Result;
import com.mojian.model.vo.PayOrderVO;
import com.mojian.service.MemberService;
import com.mojian.service.PaymentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付控制器
 */
@RestController
@RequestMapping("/pay")
@RequiredArgsConstructor
@Api(tags = "支付接口")
@Slf4j
public class PaymentController {

    private final PaymentService paymentService;
    private final JdbcTemplate jdbcTemplate;
    private final MemberService memberService;

    /**
     * 创建支付宝订单
     */
    @PostMapping("/create")
    @ApiOperation("创建支付宝订单")
    public Result<PayOrderVO> createAlipayOrder(@RequestBody PayOrderVO orderVO) {
        log.info("创建支付宝订单: {}", orderVO);
        return paymentService.createAlipayOrder(orderVO);
    }
    
    /**
     * 创建支付宝订单 - 兼容旧接口
     */
    @PostMapping("/create/order")
    @ApiOperation("创建支付宝订单(兼容旧接口)")
    public Result<PayOrderVO> createOrder(@Valid @RequestBody PayOrderVO orderVO) {
        log.info("通过兼容接口创建支付宝订单: {}", orderVO);
        return paymentService.createAlipayOrder(orderVO);
    }

    /**
     * 支付宝异步回调通知
     */
    @PostMapping("/notify")
    @ApiOperation("支付宝异步回调通知")
    public String alipayNotify(HttpServletRequest request) {
        log.info("收到支付宝回调通知");
        
        // 将请求参数转换为Map
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        
        for (String key : requestParams.keySet()) {
            String[] values = requestParams.get(key);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(key, valueStr);
            log.info("参数: {} = {}", key, valueStr);
        }
        
        // 获取订单号，判断是普通订单还是会员订单
        String orderNo = params.get("out_trade_no");
        if (orderNo != null && orderNo.startsWith("VIP")) {
            // 会员订单，调用会员服务处理
            log.info("处理会员订单支付通知: {}", orderNo);
            return memberService.handleAlipayNotify(params);
        } else {
            // 普通订单，调用支付服务处理
            log.info("处理普通订单支付通知: {}", orderNo);
            return paymentService.handleAlipayNotify(params);
        }
    }

    /**
     * 查询订单状态
     */
    @GetMapping("/query/{orderNo}")
    @ApiOperation("查询订单状态")
    public Result<PayOrderVO> queryOrder(@PathVariable String orderNo) {
        log.info("查询订单状态: {}", orderNo);
        return paymentService.checkOrderStatus(orderNo);
    }
    
    /**
     * 查询订单状态 - 兼容旧接口
     */
    @GetMapping("/check/status/{orderNo}")
    @ApiOperation("查询订单状态(兼容旧接口)")
    public Result<PayOrderVO> checkOrderStatus(@PathVariable String orderNo) {
        log.info("通过兼容接口查询订单状态: {}", orderNo);
        return paymentService.checkOrderStatus(orderNo);
    }

    /**
     * 支付成功页面
     */
    @GetMapping("/success")
    @ApiOperation("支付成功页面")
    public void paySuccess(HttpServletResponse response) throws Exception {
        log.info("跳转到支付成功页面");
        response.sendRedirect("/pay-success.html");
    }

    /**
     * 手动更新文章为免费阅读
     * 用于订单支付成功后，但文章没有自动更新为免费的情况
     */
    @PostMapping("/unlock-article/{articleId}")
    @ApiOperation("解锁已购买文章")
    public Result<Boolean> unlockArticle(@PathVariable String articleId) {
        log.info("手动解锁文章: {}", articleId);
        
        try {
            Long articleIdLong = Long.parseLong(articleId);
            
            // 更新文章的readType为1（免费）
            int affected = jdbcTemplate.update(
                "UPDATE sys_article SET read_type = 1 WHERE id = ? AND (read_type = 2 OR read_type = 3)",
                articleIdLong
            );
            
            if (affected > 0) {
                log.info("文章[{}]已手动更新为免费阅读状态", articleId);
                return Result.success(true).setMessage("文章已解锁，可以阅读完整内容");
            } else {
                log.warn("文章[{}]更新失败，可能不存在或已经是免费状态", articleId);
                return Result.success(false).setMessage("文章可能不存在或已经解锁");
            }
        } catch (Exception e) {
            log.error("手动解锁文章失败", e);
            return Result.error("解锁文章失败: " + e.getMessage());
        }
    }
} 